import contextlib
import json
import logging
import math
from datetime import date, datetime

import pandas as pd
import requests
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.core.mail import send_mail
from django.db.models import F, Q, Sum
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.http import (
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponsePermanentRedirect,
    HttpResponseRedirect,
)
from django.http.response import JsonResponse
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

import db
from customauth.models import MyUser
from tarifs.models import Uslugi, Ztarifs
from .forms import SignUpForm
from .models import (
    Buhreport,
    Container,
    Etaps,
    Images,
    It_lab,
    Mpp_podr,
    Patient,
    Pl_uslp,
    Sdl_set,
    Spr_lpu,
    Spr_opl,
    Spr_sdl,
    User_sdl,
    Zav_report,
)
from .xlsx_gen import to_xls


def index(request) -> HttpResponse:
    return render(request, "naryad/load_image.html")


def naryad_to_etap(naryad: It_lab) -> bool:
    try:
        print("naryad_to_etap")
        if Etaps.objects.filter(naryad=naryad, etap=naryad.id_etap + 1).exists():
            print("exists etap")
            return False
        if naryad.id_etap == 1:
            print("id_etap==1")
            Etaps.objects.create(
                naryad=naryad,
                etap=naryad.id_etap,
                sdl=Spr_sdl.objects.get(sdl=3500),
                dn=naryad.dn_etap,
                dz=timezone.now(),
            )
            return True
        print("other etap")
        Etaps.objects.create(
            naryad=naryad,
            etap=naryad.id_etap,
            user=MyUser.objects.get(mpp=naryad.user_etap_link.mpp),
            sdl=naryad.sdl_etap,
            dn=naryad.dn_etap,
            dz=timezone.now(),
        )
    except Exception:
        logging.exception("views naryad_to_etap error")
        return False
    else:
        return True


def naryad_move(naryad: It_lab, sdl: int = 0, mpp: int = 0, container: int = 0) -> bool:
    try:
        logging.warning(f"naryad_move({naryad.nkv}, {sdl}, {mpp})")
        if not naryad_to_etap(naryad):
            return False
        if naryad.id_etap == 0:
            naryad.id_etap = 1
            naryad.sdl_etap = Spr_sdl.objects.get(sdl=3500)
            naryad.mpp_etap = None
            naryad.user_etap_link = None
            container_used = Container.objects.get(id=container)
            container_used.used = True
            container_used.nkv = naryad.nkv
            container_used.save()
            naryad.container = container_used
            naryad.save()
            return True
        if naryad.id_etap == 1:
            naryad.id_etap = 2
            naryad.sdl_etap = Spr_sdl.objects.get(sdl=35)
            next_mpp = naryad.sdl_set.tech
            next_user = MyUser.objects.get(mpp=next_mpp)
            naryad.mpp_etap = next_user.mpp
            naryad.user_etap_link = next_user
            naryad.user_etap = next_user.login
            naryad.save()
            return True
        match sdl:
            case 1 | 1000:
                mpp = naryad.sdl_set.doc
            case 35 | 3500:
                mpp = naryad.sdl_set.tech
            case 36:
                mpp = naryad.sdl_set.pol
            case 37:
                mpp = naryad.sdl_set.lit
            case 38:
                mpp = naryad.sdl_set.cadcam
            case 39:
                mpp = naryad.sdl_set.gips
        new_user: MyUser = MyUser.objects.get(mpp=mpp)
        new_sdl: Spr_sdl = Spr_sdl.objects.get(sdl=sdl)
        naryad.id_etap += 1
        naryad.sdl_etap = new_sdl
        naryad.dn_etap = timezone.now()
        naryad.dz_etap = None
        naryad.mpp_etap = new_user.mpp
        naryad.user_etap = new_user.login
        naryad.user_etap_link = new_user
        naryad.save()
    except (ObjectDoesNotExist, MultipleObjectsReturned):
        logging.exception("naryad_move")
        return False
    except Exception:
        logging.exception("views naryad_move error")
        return False
    else:
        return True


def naryad_close_by_doc(naryad: It_lab) -> bool:
    try:
        logging.warning(f"naryad_close_by_doc({naryad.nkv})")
        naryad.pdzr = timezone.now()
        naryad.dz_etap = timezone.now()
        naryad.save()
    except Exception:
        logging.exception("naryad_close_by_doc")
        return False
    else:
        return True


def naryad_close_by_st_custom_date(naryad: It_lab, date_close: date) -> bool:  # noqa: ARG001
    try:
        logging.warning(f"naryad_close_by_doc({naryad.nkv})")
        naryad.pdzr = date_close
        # naryad.dzr = date_close
        naryad.dz_etap = date_close
        naryad.check_zav = True
        naryad.save()
    except Exception:
        logging.exception("naryad_close_by_doc")
        return False
    else:
        return True


def send_telegram(text: str) -> None:
    token = "6259020847:AAHdMHEmhQ8fJ4EU-lRdVZowxp8aTTZaJW4"  # noqa: S105
    chat_id = "-1001893335420"
    url_req = (
        "https://api.telegram.org/bot"
        + token
        + "/sendMessage"
        + "?chat_id="
        + chat_id
        + "&text="
        + text
    )
    requests.get(url_req, timeout=10)


@require_http_methods(["POST"])
def image_add(request) -> HttpResponse | HttpResponseBadRequest:
    try:
        file = request.FILES.get("image")
        nkv = request.POST.get("nkv")
        naryad = It_lab.objects.get(nkv=nkv)
        Images.objects.create(img=file, naryad=naryad)
        naryad.image_count += 1
        naryad.save()
        return HttpResponse("ok")
    except Exception as error:  # noqa: BLE001
        return HttpResponseBadRequest(str(error))


@require_http_methods(["GET"])
def image_fullscreen(request, pk) -> HttpResponse:
    image = Images.objects.get(pk=pk)
    return render(request, "naryad/image_fullscreen.html", {"image": image})


@require_http_methods(["GET"])
def delete_img(
    request,  # noqa: ARG001
    source,
    pk_naryad,
    pk_image,
) -> HttpResponseRedirect | HttpResponsePermanentRedirect:
    if source == "upd":
        Images.objects.get(pk=pk_image).delete()
        return redirect("/naryad/naryad_upd/" + str(pk_naryad))
    return redirect("/naryad/naryad_list")


sql_uslugi_load = """select pl_uslp.kusl,n_usl.nusl,pl_uslp.kol,pl_uslp.price,pl_uslp.stu
from pl_uslp, n_usl
where pl_uslp.usl=n_usl.usl
 and pl_uslp.idkv='{idkv}'"""


def signup(
    request,
) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse:
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            # load the profile instance created by the signal
            user.save()

            # login user after signing up

            # redirect user to home page
            return redirect("home")
    else:
        form = SignUpForm()
    return render(request, "registration/signup.html", {"form": form})


@require_http_methods(["POST", "GET"])
def login_vue(request, username, password):  # noqa: ANN201, PLR0912, C901
    username_post = request.POST["username"]
    password_post = request.POST["password"]
    if request.method == "POST":
        user: MyUser = authenticate(
            request,
            username=username_post,
            password=password_post,
        )
        if user is not None:
            try:
                user_auth = User_sdl.objects.get(user=user)
                dolzh = ""
                if len(user_auth.dolzh().split(", ")) > 1:
                    dolzh_all = user_auth.dolzh().split(", ")
                    if "Старший техник" in dolzh_all:
                        dolzh = "Старший техник"
                    elif "Зав. ортопедией" in dolzh_all:
                        dolzh = "Зав. ортопедией"
                else:
                    dolzh2 = user_auth.dolzh()
                    dolzh = dolzh2[0] if isinstance(dolzh2, list) else dolzh2

                access = ""
                if len(user_auth.access_list()) > 1:
                    access_all = user_auth.access_list()
                    if "tech_st" in access_all:
                        access = "tech_st"
                    elif "zav_ort" in access_all:
                        access = "zav_ort"
                else:
                    access = user_auth.access_list()[0]
                return JsonResponse(
                    {
                        "status": "ok",
                        "username": user.login,
                        "mpp": user.mpp,
                        "dolzh": dolzh,
                        "access": access,
                        "fio_short": user_auth.fio_short(),
                    },
                )
            except Exception as e:
                logging.exception("Found an error")
                return JsonResponse({"status": "error", "message": e})
    if username is not None and password is not None:
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect("naryad_list")
    return redirect("login")


@require_http_methods(["GET"])
def spec_by_prof(request) -> JsonResponse:  # noqa: ARG001
    try:
        dict_zero = {"id": 0, "name": "He назначен", "mpp": 0}
        list_tech = User_sdl.objects.filter(access__access="tech")
        tech_list = [dict_zero]
        for tech in list_tech:
            new_dict = {
                "id": tech.user.id,
                "name": tech.user.get_full_name(),
                "mpp": tech.user.mpp,
            }
            tech_list.append(new_dict)
        list_lit = User_sdl.objects.filter(access__access="lit")
        lit_list = [dict_zero]
        for lit in list_lit:
            new_dict = {
                "id": lit.user.id,
                "name": lit.user.get_full_name(),
                "mpp": lit.user.mpp,
            }
            lit_list.append(new_dict)
        list_cadcam = User_sdl.objects.filter(access__access="cad")
        cadcam_list = [dict_zero]
        for cadcam in list_cadcam:
            new_dict = {
                "id": cadcam.user.id,
                "name": cadcam.user.get_full_name(),
                "mpp": cadcam.user.mpp,
            }
            cadcam_list.append(new_dict)
        list_pol = User_sdl.objects.filter(access__access="pol")
        pol_list = [dict_zero]
        for pol in list_pol:
            new_dict = {
                "id": pol.user.id,
                "name": pol.user.get_full_name(),
                "mpp": pol.user.mpp,
            }
            pol_list.append(new_dict)
        return JsonResponse(
            {
                "status": "ok",
                "list_tech": tech_list,
                "list_lit": lit_list,
                "list_cadcam": cadcam_list,
                "list_pol": pol_list,
            },
        )
    except Exception as inst:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": inst})


@require_http_methods(["POST"])
def sdl_set_update(request) -> JsonResponse:
    try:
        ids = request.POST["id"]
        sdl_set = Sdl_set.objects.get(id=ids)
        if request.POST["tech"]:
            sdl_set.tech = request.POST["tech"]
        if request.POST["lit"]:
            sdl_set.lit = request.POST["lit"]
        if request.POST["pol"]:
            sdl_set.pol = request.POST["pol"]
        if request.POST["cadcam"]:
            sdl_set.cadcam = request.POST["cadcam"]
        sdl_set.save()
        all_etaps = It_lab.objects.filter(sdl_set=sdl_set, id_etap__gt=2).only("id")
        for etap in all_etaps:
            match etap.sdl_etap.sdl:
                case 35:
                    user: MyUser = MyUser.objects.get(mpp=sdl_set.tech)
                case 36:
                    user: MyUser = MyUser.objects.get(mpp=sdl_set.pol)
                case 37:
                    user: MyUser = MyUser.objects.get(mpp=sdl_set.lit)
                case 38:
                    user: MyUser = MyUser.objects.get(mpp=sdl_set.cadcam)
                case _:
                    continue
            etap.mpp_etap = user.mpp
            etap.user_etap_link = user
            etap.user_etap = user.login
            etap.save()

        return JsonResponse({"status": "ok"})
    except Exception as inst:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": str(inst)})


@require_http_methods(["GET"])
def get_usl_by_idkv(request, idkv: int) -> JsonResponse:  # noqa: ARG001
    try:
        usls = Pl_uslp.objects.filter(idkv=idkv).all()
        return JsonResponse({"status": "ok", "usl": usls})
    except Exception as inst:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": inst})


@require_http_methods(["GET"])
def get_stat_for_zav(request) -> JsonResponse:  # noqa: ARG001
    try:
        count_nar_income = It_lab.objects.filter(id_etap=0).count()
        count_nar_rasp = It_lab.objects.filter(id_etap=1).count()
        count_nar_lab = It_lab.objects.filter(id_etap=2).count()
        tech_inwork_nar_id = (
            It_lab.objects.exclude(dz_etap__isnull=False)
            .filter(sdl_etap__sdl=35)
            .values_list("id")
        )
        doc_inwork_nar_id = (
            It_lab.objects.exclude(dz_etap__isnull=False)
            .filter(sdl_etap__sdl=1)
            .values_list("id")
        )
        techs_inwork_nar = {}
        for nar in tech_inwork_nar_id:
            tech = It_lab.objects.get(id=nar[0]).user_etap_link
            tech_short_name = tech.get_short_name()
            tech_mpp = tech.mpp
            if tech in techs_inwork_nar:
                techs_inwork_nar[tech][1] += 1
            else:
                tech_info_list = [tech_short_name, 1, tech_mpp]
                techs_inwork_nar[tech_short_name] = tech_info_list
        doc_inwork_nar = {}
        for nar in doc_inwork_nar_id:
            doc = It_lab.objects.get(id=nar[0]).user_etap_link
            doc_short_name = doc.get_short_name()
            doc_mpp = doc.mpp
            if doc in doc_inwork_nar:
                doc_inwork_nar[doc][1] += 1
            else:
                doc_info_list = [doc_short_name, 1, doc_mpp]
                doc_inwork_nar[doc_short_name] = doc_info_list
        return JsonResponse(
            {
                "count_nar_income": count_nar_income,
                "count_nar_rasp": count_nar_rasp,
                "count_nar_lab": count_nar_lab,
                "techs_inwork_nar": techs_inwork_nar,
                "doc_inwork_nar": doc_inwork_nar,
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["POST"])
@csrf_exempt
def get_stat_for_doc(request, mpp) -> JsonResponse:
    dn_lg = request.POST.get("dn_lg")
    dn_lg = datetime.strptime(dn_lg, "%d.%m.%Y")
    dk_lg = request.POST.get("dk_lg")
    dk_lg = datetime.strptime(dk_lg, "%d.%m.%Y")
    dn_pl = request.POST.get("dn_pl")
    dn_pl = datetime.strptime(dn_pl, "%d.%m.%Y")
    dk_pl = request.POST.get("dk_pl")
    dk_pl = datetime.strptime(dk_pl, "%d.%m.%Y")
    try:
        date_start_lgot = dn_lg
        date_end_lgot = dk_lg
        date_start_pd = dn_pl
        date_end_pd = dk_pl
        count_nar_done_lgot = It_lab.objects.filter(
            mpp_etap=mpp,
            dzr__range=(date_start_lgot, date_end_lgot),
            opl__opl=1,
        ).count()
        count_nar_done_pd = It_lab.objects.filter(
            mpp_etap=mpp,
            dzr__range=[date_start_pd, date_end_pd],
            opl__opl__in=[100, 10, 5, 3],
        ).count()
        count_nar_open_lgot = It_lab.objects.filter(
            dzr__isnull=True,
            mpp_etap=mpp,
            opl__opl=1,
        ).count()
        count_nar_open_pd = It_lab.objects.filter(
            dzr__isnull=True,
            mpp_etap=mpp,
            opl__opl__in=[100, 10, 5, 3],
        ).count()
        doc_finish_nar_lgot_sum = It_lab.objects.filter(
            mpp_etap=mpp,
            dzr__range=(date_start_lgot, date_end_lgot),
            opl__opl=1,
        ).aggregate(sum=Sum("stu"))["sum"]
        doc_pdr_nar_lgot_sum = It_lab.objects.filter(
            mpp_etap=mpp,
            pdzr__range=(date_start_lgot, date_end_lgot),
            dzr__isnull=True,
            opl__opl=1,
        ).aggregate(sum=Sum("stu"))["sum"]
        doc_finish_nar_pd_sum = It_lab.objects.filter(
            mpp_etap=mpp,
            dzr__range=[date_start_pd, date_end_pd],
            opl__opl__in=[100, 10, 5, 3],
        ).aggregate(sum=Sum("stu"))["sum"]
        doc_pdr_nar_pd_sum = It_lab.objects.filter(
            mpp_etap=mpp,
            pdzr__range=[date_start_pd, date_end_pd],
            dzr__isnull=True,
            opl__opl__in=[100, 10, 5, 3],
        ).aggregate(sum=Sum("stu"))["sum"]
        doc_finish_nar_lgot = list(
            It_lab.objects.filter(
                mpp_etap=mpp,
                dzr__range=(date_start_lgot, date_end_lgot),
                opl__opl=1,
            )
            .select_related("patient")
            .values(
                "idkv",
                "nkv",
                "patient__fam",
                "patient__im",
                "patient__ot",
                "stu",
                "dou",
                "dzr",
                "lpu__name_lpu",
            ),
        )
        doc_pdr_nar_lgot = list(
            It_lab.objects.filter(
                mpp_etap=mpp,
                pdzr__range=(date_start_lgot, date_end_lgot),
                dzr__isnull=True,
                opl__opl=1,
            )
            .select_related("patient")
            .values(
                "idkv",
                "nkv",
                "patient__fam",
                "patient__im",
                "patient__ot",
                "stu",
                "dou",
                "dzr",
                "lpu__name_lpu",
            ),
        )
        doc_finish_nar_pd = list(
            It_lab.objects.filter(
                mpp_etap=mpp,
                dzr__range=[date_start_pd, date_end_pd],
                opl__opl__in=[100, 10, 5, 3],
            )
            .select_related("patient")
            .values(
                "idkv",
                "nkv",
                "patient__fam",
                "patient__im",
                "patient__ot",
                "stu",
                "dou",
                "dzr",
                "lpu__name_lpu",
            ),
        )
        doc_pdr_nar_pd = list(
            It_lab.objects.filter(
                mpp_etap=mpp,
                pdzr__range=[date_start_pd, date_end_pd],
                dzr__isnull=True,
                opl__opl__in=[100, 10, 5, 3],
            )
            .select_related("patient")
            .values(
                "idkv",
                "nkv",
                "patient__fam",
                "patient__im",
                "patient__ot",
                "stu",
                "dou",
                "dzr",
                "lpu__name_lpu",
            ),
        )
        print("doc_finish_nar_pd_sum", doc_finish_nar_pd_sum)
        return JsonResponse(
            {
                "count_nar_done_lgot": count_nar_done_lgot,
                "count_nar_done_pd": count_nar_done_pd,
                "count_nar_open_lgot": count_nar_open_lgot,
                "count_nar_open_pd": count_nar_open_pd,
                "doc_finish_nar_lgot_sum": doc_finish_nar_lgot_sum,
                "doc_finish_nar_pd_sum": doc_finish_nar_pd_sum,
                "doc_finish_nar_lgot": doc_finish_nar_lgot,
                "doc_finish_nar_pd": doc_finish_nar_pd,
                "doc_pdr_nar_lgot_sum": doc_pdr_nar_lgot_sum,
                "doc_pdr_nar_pd_sum": doc_pdr_nar_pd_sum,
                "doc_pdr_nar_lgot": doc_pdr_nar_lgot,
                "doc_pdr_nar_pd": doc_pdr_nar_pd,
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["GET"])
def period_date(request) -> JsonResponse:  # noqa: ARG001
    select_dates = "select id, nmonth, dn_pl, dk_pl, dn_lg, dk_lg, years, months from it_period_rep where razdel=1"
    try:
        dates = db.sel_dict_in_list_desc(select_dates)
        return JsonResponse(
            {
                "dates": dates,
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["POST"])
@csrf_exempt
def get_nar_usl_doc(request, mpp) -> JsonResponse:
    dn_lg = request.POST.get("dn_lg")
    dn_lg = datetime.strptime(dn_lg, "%d.%m.%Y")
    dk_lg = request.POST.get("dk_lg")
    dk_lg = datetime.strptime(dk_lg, "%d.%m.%Y")
    dn_pl = request.POST.get("dn_pl")
    dn_pl = datetime.strptime(dn_pl, "%d.%m.%Y")
    dk_pl = request.POST.get("dk_pl")
    dk_pl = datetime.strptime(dk_pl, "%d.%m.%Y")
    print(dn_lg, dk_lg, dn_pl, dk_pl)
    try:
        date_start_lgot = dn_lg
        date_end_lgot = dk_lg
        date_start_pd = dn_pl
        date_end_pd = dk_pl

        request_lgot = f"""
            select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr, pl_uslk.lpu
            from patient, pl_uslk
            where patient.uid=pl_uslk.uid
            and pdog=0
            and gr_otd=2
            and vr={mpp}
            and opl=1
            and dzr>='{date_start_lgot}'
            and dzr<='{date_end_lgot}'
            and status in (2, 3)"""  # noqa: S608
        doc_finish_nar_usl_lgot = db.sel_dict_in_list_desc(request_lgot)
        for nar in doc_finish_nar_usl_lgot:
            nar["name_lpu"] = Spr_lpu.objects.filter(lpu=nar["LPU"]).first().name_lpu
        count_finish_nar_usl_lgot = len(doc_finish_nar_usl_lgot)
        sum_lgot = sum([x["STU"] for x in doc_finish_nar_usl_lgot])
        request_pdr_lgot = f"""
            select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr, pl_uslk.lpu
            from patient, pl_uslk
            where patient.uid=pl_uslk.uid
            and pdog=0
            and gr_otd=2
            and vr={mpp}
            and opl=1
            and dzr>='{date_start_lgot}'
            and dzr<='{date_end_lgot}'
            and status in (5, 6)"""  # noqa: S608
        doc_pdr_nar_usl_lgot = db.sel_dict_in_list_desc(request_pdr_lgot)
        for nar in doc_pdr_nar_usl_lgot:
            nar["name_lpu"] = Spr_lpu.objects.filter(lpu=nar["LPU"]).first().name_lpu
        pdr_sum_lgot = sum([x["STU"] for x in doc_pdr_nar_usl_lgot])
        request_pd = f"""
            select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr, pl_uslk.lpu
            from patient, pl_uslk
            where patient.uid=pl_uslk.uid
            and pdog=0
            and gr_otd=2
            and vr={mpp}
            and opl in (3, 5, 10, 100)
            and dzr>='{date_start_pd}'
            and dzr<='{date_end_pd}'
            and status in (2, 3)"""  # noqa: S608
        doc_finish_nar_usl_pd = db.sel_dict_in_list_desc(request_pd)
        for nar in doc_finish_nar_usl_pd:
            nar["name_lpu"] = Spr_lpu.objects.filter(lpu=nar["LPU"]).first().name_lpu
        count_finish_nar_usl_pd = len(doc_finish_nar_usl_pd)
        sum_pd = sum([x["STU"] for x in doc_finish_nar_usl_pd])
        request_pdr_pd = f"""
            select pl_uslk.nkv, patient.fam, patient.im, patient.ot, pl_uslk.stu, pl_uslk.dou, pl_uslk.dzr, pl_uslk.lpu
            from patient, pl_uslk
            where patient.uid=pl_uslk.uid
            and pdog=0 and gr_otd=2
            and vr={mpp} and opl in (3, 5, 10, 100)
            and dzr>='{date_start_pd}'
            and dzr<='{date_end_pd}'
            and status in (5, 6)"""  # noqa: S608
        doc_pdr_nar_usl_pd = db.sel_dict_in_list_desc(request_pdr_pd)
        for nar in doc_pdr_nar_usl_pd:
            nar["name_lpu"] = Spr_lpu.objects.filter(lpu=nar["LPU"]).first().name_lpu
        pdr_sum_pd = sum([x["STU"] for x in doc_pdr_nar_usl_pd])
        return JsonResponse(
            {
                "doc_finish_nar_usl_lgot": doc_finish_nar_usl_lgot,
                "doc_finish_nar_usl_pd": doc_finish_nar_usl_pd,
                "count_finish_nar_usl_lgot": count_finish_nar_usl_lgot,
                "count_finish_nar_usl_pd": count_finish_nar_usl_pd,
                "sum_lgot": sum_lgot,
                "sum_pd": sum_pd,
                "doc_pdr_nar_usl_lgot": doc_pdr_nar_usl_lgot,
                "doc_pdr_nar_usl_pd": doc_pdr_nar_usl_pd,
                "pdr_sum_lgot": pdr_sum_lgot,
                "pdr_sum_pd": pdr_sum_pd,
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["GET"])
def close_usl_nar(request, naryad) -> JsonResponse:
    today = datetime.date.today().strftime("%d.%m.%Y")
    request = f"update pl_uslk set dzr='{today}', status=5 where nkv={naryad}"  # noqa: S608
    try:
        db.write(request)
        request_result = db.sel_dict_in_list_desc(request)
        return JsonResponse(
            {
                "naryad": request_result,
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["GET"])
def resend_nar_lab(request) -> JsonResponse:
    request = "update pl_uslk set status_exp=0 where dzr is null and dou>='08.06.2023' and status_exp=201"
    try:
        db.write(request)
    except Exception:
        logging.exception("Found an error")
    return JsonResponse(
        {
            "naryad": "done",
        },
    )


@require_http_methods(["GET"])
def del_nar(request, naryad) -> JsonResponse:  # noqa: ARG001
    try:
        It_lab.objects.filter(idkv=naryad).delete()
        return JsonResponse(
            {
                "ok": "deleted",
            },
        )
    except Exception as exc:
        logging.exception("Found an error")
        return JsonResponse({"error": exc})


@require_http_methods(["GET"])
def get_container(request, container) -> JsonResponse | None:  # noqa: ARG001
    if 1 <= container <= 1000:  # noqa: PLR2004
        info_container: Container = Container.objects.get(id=container)
        if info_container.used:
            naryads_container: int = It_lab.objects.filter(
                nkv=info_container.nkv,
                id_etap=0,
                dzr__isnull=True,
                pdzr__isnull=True,
            ).count()
            if naryads_container > 0:
                return JsonResponse({"free": False})
        return JsonResponse(
            {
                "free": True,
            },
        )
    return JsonResponse(
        {
            "free": False,
        },
    )


@require_http_methods(["GET"])
def container_info(request, container_id) -> JsonResponse:  # noqa: ARG001
    query_info = Container.objects.filter(id=container_id).first()
    if query_info is None:
        return JsonResponse({"used": False})
    if query_info.used is False:
        if query_info.nkv > 0:
            query_info.nkv = 0
            query_info.save()
        return JsonResponse({"used": False})
    info = query_info.get_info()
    if info is False:
        return JsonResponse({"used": False})
    return JsonResponse({"used": True, "info": info})


@require_http_methods(["GET"])
def bonus_naryad(request, naryad_id) -> JsonResponse:  # noqa: ARG001
    current_naryad = It_lab.objects.get(id=naryad_id)
    with contextlib.suppress(Exception):
        other_naryads = (
            It_lab.objects.exclude(nkv=current_naryad.nkv)
            .exclude(container=Container.objects.get(id=0))
            .filter(
                patient=current_naryad.patient,
                dzr__isnull=True,
                sdl_set__doc=current_naryad.sdl_set.doc,
            )
            .values("id", "nkv", "stu", "container", "container__id", "container__nkv")
        )

    if other_naryads:
        return JsonResponse({"open_naryads": True, "naryads": list(other_naryads)})
    return JsonResponse({"open_naryads": False})


@require_http_methods(["POST"])
def zav_report_finish(request) -> JsonResponse:  # noqa: C901, PLR0915, PLR0912
    nars_lab_all = request.POST["nars_lab_all"]
    nars_lab_ok = request.POST["nars_lab_ok"]
    usl_numbers = request.POST["usl_numbers_all"]
    nars_usl_ok = request.POST["nars_usl_ok"]
    dn = request.POST["dn"]
    dk = request.POST["dk"]
    opl = request.POST["opl"]
    year = request.POST["year"]
    month = request.POST["month"]
    mpp = request.POST["mpp"]

    nars_lab_all = json.loads(nars_lab_all)
    usl_numbers = json.loads(usl_numbers)
    nars_lab_ok = json.loads(nars_lab_ok)
    nars_usl_ok = json.loads(nars_usl_ok)
    nar_list = []
    for one_nar in nars_lab_ok:
        It_lab.objects.filter(nkv=one_nar["nkv"]).update(check_zav=True)
        nar_list.append(one_nar["nkv"])
    for one_usl in nars_usl_ok:
        nar_list.append(one_usl["nkv"])  # noqa: PERF401
    nar_tuple = tuple(nar_list)
    sql_part1 = f"nkv={nar_list[0]}" if len(nar_list) == 1 else f"nkv in {nar_tuple}"
    try:
        db.write(f"Update pl_uslk set status=6 where {sql_part1}")  # noqa: S608
    except Exception:
        logging.exception("Found an error")
    stu_lab = 0
    for nar in nars_lab_ok:
        stu_lab += nar["stu"]
    stu_usl = 0
    for usl in nars_usl_ok:
        stu_usl += usl["stu"]
    stu_all = stu_lab + stu_usl
    nars_lab_cancel = nars_lab_all.copy()
    for one in nars_lab_ok:
        if one["nkv"] in nars_lab_cancel:
            nars_lab_cancel.remove(one["nkv"])
    nars_usl_cancel = usl_numbers.copy()
    for two in nars_usl_ok:
        if two["nkv"] in nars_usl_cancel:
            nars_usl_cancel.remove(two["nkv"])
    kol_lab = len(nars_lab_ok)
    kol_usl = len(nars_usl_ok)
    kol_all = kol_lab + kol_usl
    opl2 = opl.split(",")
    opl_new = []
    for one in opl2:
        opl_new.append(int(one))  # noqa: PERF401
    try:
        if Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).exists():
            Zav_report.objects.filter(mpp=mpp, year=year, month=month, opl=opl).update(
                kol_lab=kol_lab,
                kol_usl=kol_usl,
                kol_all=kol_all,
                stu_lab=stu_lab,
                stu_usl=stu_usl,
                stu_all=stu_all,
                nars_lab=nars_lab_ok,
                nars_usl=nars_usl_ok,
                nars_lab_cancel=nars_lab_cancel,
                nars_usl_cancel=nars_usl_cancel,
            )
        else:
            Zav_report.objects.create(
                mpp=mpp,
                year=year,
                month=month,
                dn=dn,
                dk=dk,
                opl=opl,
                kol_lab=kol_lab,
                kol_usl=kol_usl,
                kol_all=kol_all,
                stu_lab=stu_lab,
                stu_usl=stu_usl,
                stu_all=stu_all,
                nars_lab=nars_lab_ok,
                nars_usl=nars_usl_ok,
                nars_lab_cancel=nars_lab_cancel,
                nars_usl_cancel=nars_usl_cancel,
            )
        nar_cancel_list = []
        for nar in nars_lab_cancel:
            naryad = It_lab.objects.filter(nkv=nar).order_by("-id_etap").first()
            naryad.dzr = None
            naryad.dz_etap = None
            naryad.save()
            It_lab.objects.filter(nkv=nar).update(dzr=None, pdzr=None)
            naryad_open_last_etap = (
                It_lab.objects.filter(nkv=nar).order_by("-id_etap").first()
            )
            naryad_open_last_etap.dz_etap = None
            naryad_open_last_etap.save()
            nar_cancel_list.append(nar)
        for nar in nars_usl_cancel:
            nar_cancel_list.append(nar)  # noqa: PERF402
        nar_cancel_tuple = tuple(nar_cancel_list)
        sql_part = (
            f"nkv={nar_cancel_list[0]}"
            if len(nar_cancel_list) == 1
            else f"nkv in {nar_cancel_tuple}"
        )
        try:
            db.write(f"update pl_uslk set dzr=null, status=2 where {sql_part}")  # noqa: S608
        except Exception:
            logging.exception("Found an error")
        dn = datetime.strptime(dn, "%d.%m.%Y")
        dn = dn.strftime("%Y-%m-%d")
        dk = datetime.strptime(dk, "%d.%m.%Y")
        dk = dk.strftime("%Y-%m-%d")
        docs_finish = (
            It_lab.objects.filter(
                id_etap=0,
                dzr__range=[dn, dk],
                sdl_set__doc=mpp,
                opl__opl__in=opl_new,
            )
            .select_related("patient")
            .values(
                "idkv",
                "nkv",
                "patient__fam",
                "patient__im",
                "patient__ot",
                "stu",
                "dou",
                "dzr",
                "sdl_set__doc",
            )
        )
        docs_finish_list = list(docs_finish)
        list_pd = ["Фамилия доктора", mpp]
        doc_finish_nar_pd_sum = 0
        doc_finish_pd = []
        for naryad in docs_finish_list:
            doc_finish_nar_pd_sum += naryad["stu"]
            doc_finish_pd.append(naryad)
        list_pd.append(doc_finish_pd)
        list_pd.append(len(doc_finish_pd))

        if doc_finish_nar_pd_sum is None:
            doc_finish_nar_pd_sum = 0
        list_pd.append(doc_finish_nar_pd_sum)

        select_pd = f"""select n_mpp.fam as doctorname, patient.fam, patient.im, patient.ot, pl_uslk.idkv, pl_uslk.nkv,
        pl_uslk.dou, pl_uslk.dzr, pl_uslk.stu from pl_uslk, n_mpp, patient
        where pl_uslk.vr=n_mpp.mpp
        and pl_uslk.uid=patient.uid
        and vr={mpp}
        and pdog=0
        and opl in ({opl})
        and dzr>='{dn}'
        and dzr<='{dk}'
        and status in (2, 3)"""  # noqa: S608
        pd_usl = db.sel_dict_in_list_desc(select_pd)
        list_pd.append(pd_usl)

        pd_sum_usl = 0
        for usl in pd_usl:
            pd_sum_usl += usl["STU"]
        list_pd.append(pd_sum_usl)

        # Добавляем периоды выборки для сверки на фронте
        list_pd.append(dn)
        list_pd.append(dk)

        list_pd.append(opl)

        return JsonResponse({"status": "ok", "list_nar": list_pd})
    except Exception as inst:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": inst})


@require_http_methods(["GET"])
def service_add_podr_to_zav(request) -> JsonResponse:  # noqa: ARG001
    podr_list = [
        {"lpu_name": "Березовское стоматологическое отделение", "lpu_number": 3},
        {"lpu_name": "Яшкинское стоматологическое отделение", "lpu_number": 32},
        {"lpu_name": "Поликлиника №5", "lpu_number": 245},
        {"lpu_name": "Стоматологическое отделение", "lpu_number": 243},
        {"lpu_name": "Поликлиника №4", "lpu_number": 236},
        {"lpu_name": "Поликлиника №3", "lpu_number": 165},
        {"lpu_name": "Поликлиника №2", "lpu_number": 164},
        {"lpu_name": "Поликлиника №1", "lpu_number": 162},
        {"lpu_name": "Топкинское стоматологическое отделение", "lpu_number": 28},
    ]
    zav = MyUser.objects.get(mpp=111)
    try:
        Mpp_podr.objects.create(mpp=zav, podr=podr_list)
    except Exception:
        logging.exception("Found an error")
    return JsonResponse({"status": "ok"})


@require_http_methods(["GET"])
def mpp_podr_list(request, mpp: int) -> JsonResponse:  # noqa: ARG001
    user = MyUser.objects.filter(mpp=mpp).first()
    mpp_podr = Mpp_podr.objects.filter(mpp=user).first()
    list_podr = mpp_podr.podr
    if user is not None and list_podr is not None:
        return JsonResponse({"status": "ok", "list_podr": list_podr})
    return JsonResponse(
        {
            "status": "error",
            "list_podr": [],
            "text": f"user: {user}, list_podr: {list_podr}",
        },
    )


@require_http_methods(["GET"])
def get_brigades(request, nkv: int) -> JsonResponse:  # noqa: ARG001
    naryad: It_lab | None = It_lab.objects.filter(id_etap=0, nkv=nkv).first()
    if naryad:
        mpp_tech: int = naryad.sdl_set.tech
        mpp_lit: int = naryad.sdl_set.lit
        mpp_pol: int = naryad.sdl_set.pol
        mpp_cadcam: int = naryad.sdl_set.cadcam
        name_tech: str = (
            (MyUser.objects.get(mpp=mpp_tech)).get_full_name() if mpp_tech > 0 else ""
        )
        name_lit: str = (
            (MyUser.objects.get(mpp=mpp_lit)).get_full_name() if mpp_lit > 0 else ""
        )
        name_pol: str = (
            (MyUser.objects.get(mpp=mpp_pol)).get_full_name() if mpp_pol > 0 else ""
        )
        name_cadcam: str = (
            (MyUser.objects.get(mpp=mpp_cadcam)).get_full_name()
            if mpp_cadcam > 0
            else ""
        )
        dict_tech: dict[str, int | str] = {"mpp": mpp_tech, "name": name_tech}
        dict_lit: dict[str, int | str] = {"mpp": mpp_lit, "name": name_lit}
        dict_pol: dict[str, int | str] = {"mpp": mpp_pol, "name": name_pol}
        dict_cadcam: dict[str, int | str] = {"mpp": mpp_cadcam, "name": name_cadcam}
        result_dict: dict[str, dict] = {
            "tech": dict_tech,
            "lit": dict_lit,
            "pol": dict_pol,
            "cadcam": dict_cadcam,
        }
        return JsonResponse({"status": "ok", "brigade": result_dict})
    return None


@require_http_methods(["GET"])
def get_list_spec(
    request,  # noqa: ARG001
) -> JsonResponse:
    list_tech = User_sdl.objects.filter(sdls__sdl=35)
    list_tech_done: list[dict[str, int | str]] = [
        {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_tech
    ]
    list_lit = User_sdl.objects.filter(sdls__sdl=37)
    list_lit_done: list[dict[str, int | str]] = [
        {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_lit
    ]
    list_pol = User_sdl.objects.filter(sdls__sdl=36)
    list_pol_done: list[dict[str, int | str]] = [
        {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_pol
    ]
    list_cadcam = User_sdl.objects.filter(sdls__sdl=38)
    list_cadcam_done: list[dict[str, int | str]] = [
        {"mpp": x.user.mpp, "name": x.fio(), "fio": x.fio_short()} for x in list_cadcam
    ]
    dict_brigade: dict[str, list] = {
        "tech": list_tech_done,
        "lit": list_lit_done,
        "pol": list_pol_done,
        "cadcam": list_cadcam_done,
    }
    return JsonResponse({"status": "ok", "brigade": dict_brigade})


@require_http_methods(["GET"])
def finish_nar_by_st(request, nkv: int, lab: int = 0) -> JsonResponse:  # noqa: ARG001
    naryad = It_lab.objects.filter(nkv=nkv, id_etap=0).first()
    try:
        if lab == 0:
            It_lab.objects.filter(nkv=nkv).update(check_tech=True, dzr=naryad.pdzr)
        db.write(f"update pl_uslk set status=2 where nkv={nkv}")  # noqa: S608
    except Exception as error:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": error})
    return JsonResponse({"status": "ok", "message": "Успешно записано"})


@require_http_methods(["GET"])
def get_brigade_arena(request, nkv: int) -> JsonResponse:  # noqa: ARG001
    naryad = It_lab.objects.filter(nkv=nkv, id_etap=0).first()
    dict_result: dict[str, int] = {"tech": 0, "lit": 0, "pol": 0, "cadcam": 0}
    try:
        result = db.sel_dict_in_list_lowerkeys(
            f"select * from pl_uslb where idkv={naryad.idkv}",  # noqa: S608
        )
        for one in result:
            if one["sdl"] == 35:  # noqa: PLR2004
                dict_result["tech"] = one["mpp"]
            if one["sdl"] == 37:  # noqa: PLR2004
                dict_result["lit"] = one["mpp"]
            if one["sdl"] == 36:  # noqa: PLR2004
                dict_result["pol"] = one["mpp"]
            if one["sdl"] == 38:  # noqa: PLR2004
                dict_result["cadcam"] = one["mpp"]
    except Exception as error:
        logging.exception("Found an error")
        return JsonResponse({"status": "error", "message": error})
    return JsonResponse({"status": "ok", "brigade": dict_result})


def get_lgot_columns(request) -> JsonResponse:  # noqa: ARG001
    dict_lgot: dict[int, str] = {
        3: "Участники BOB",
        4: "Ветераны боевых действий",
        6: "Бывшие несовершеннолетние узники концлагерей",
        7: "Лица, подвергшиеся политическим репрессиям",
        8: """Военнослужащие, проход. военную службу (1941-45r.) в воинских частях, не входящих в состав
        действ.армии и нагр. медалями""",
        9: "Труженики тыла, проработавшие в тылу не менее 6-ти месяцев, награжденные орденами и медалями",
        12: "Дети до 3-x лет",
        13: "Дети многодетных семей до 6 лет",
        14: "Дети инвалиды в возрасте до 18 лет.",
        40: "Родители, вдовы, дети военносл., погибших при исполнении служебного долга",
        41: "Блокадники Ленинграда, награжденные медалью",
        43: "Родители и жены погиб.военносл., приравн. к участн.BOB",
        73: "Многодетная мать",
        105: "Родители, вдовы ИВОВ, УВОВ, Героев Советского Союза и пр.",
        112: "Ветераны труда",
    }

    list_lgot: list[dict[str, str]] = [{"key": "name", "label": "Врач"}]

    for key in dict_lgot:
        list_lgot.append({"key": f"nktn_{key}", "label": dict_lgot[key]})
        list_lgot.append({"key": f"kol_{key}", "label": "Кол-во"})
        list_lgot.append({"key": f"kol_{key}", "label": "Стоимость"})

    return JsonResponse({"status": "ok", "list_lgot": list_lgot})


def lgot_edit(dict_in: dict) -> None:
    x = dict_in["ktn"]
    dict_in[f"ktn_{x}"] = dict_in.pop("ktn")
    dict_in[f"nktn_{x}"] = dict_in.pop("nktn")
    dict_in[f"kol_{x}"] = dict_in.pop("kol")
    dict_in[f"stu_{x}"] = dict_in.pop("stu")


def get_lgot_by_mpp(request, mpp: int) -> JsonResponse:  # noqa: PLR0912, C901, ARG001
    dict_lgot: dict[int, str] = {
        3: "Участники BOB",
        4: "Ветераны боевых действий",
        6: "Бывшие несовершеннолетние узники концлагерей",
        7: "Лица, подвергшиеся политическим репрессиям",
        8: """Военнослужащие, проход. военную службу (1941-45r.) в воинских частях, не входящих
        в состав действ. армии и нагр. медалями""",
        9: "Труженики тыла, проработавшие в тылу не менее 6-ти месяцев, награжденные орденами и медалями",
        12: "Дети до 3-x лет",
        13: "Дети многодетных семей до 6 лет",
        # 14: "Дети инвалиды в возрасте до 18 лет.",
        14: "Многодетные матери",
        15: "Соц.поддержка",
        40: "Родители, вдовы, дети военносл., погибших при исполнении служебного долга",
        41: "Блокадники Ленинграда, награжденные медалью",
        43: "Родители и жены погиб.военносл., приравн. к участн.BOB",
        73: "Многодетная мать",
        # 105: "Родители, вдовы ИВОВ, УВОВ, Героев Советского Союза и пр.",  # noqa: RUF003
        105: "Ветераны труда",
        112: "Ветераны труда",
        114: "Реабилитированные лица",
    }

    lgot_114: tuple = (7,)
    lgot_105: tuple = (9, 112)
    lgot_15: tuple = (41, 40, 3, 6, 105, 8, 43)
    lgot_14: tuple = (73,)

    podr_list: Mpp_podr | None = Mpp_podr.objects.filter(mpp__mpp=mpp).first()
    list_podr = [x["lpu_number"] for x in podr_list.podr]
    result = db.sel_dict_in_list_lowerkeys(
        f"""select lpu, vr as mpp,ktn,
        (select distinct nktn from n_ktn where ktn=pl_uslk.ktn) as nktn,
        count(nkv) as kol,cast(sum(stu) as integer) as stu
        from pl_uslk
        where dzr is null
        and (opl=1)
        and (gr_otd=2)
        and (status=2)
        and dto >='01.01.2022'
        and ktn in (3, 6, 7, 8, 9, 40, 41, 43, 73, 105, 112)
        and lpu in {tuple(list_podr)}
        group by lpu, mpp,ktn,nktn""",  # noqa: S608
    )
    list_lpu = Spr_lpu.objects.all().values("name_lpu", "lpu")
    dict_lpu = {}
    for lpu in list_lpu:
        dict_lpu[lpu["lpu"]] = lpu["name_lpu"]
    list_doc = list(MyUser.objects.all().values("mpp", "fam", "im", "ot"))
    list_doc = [
        {"mpp": x["mpp"], "name": f"{x['fam']} {x['im'][0]}. {x['ot'][0]}."}
        for x in list_doc
    ]
    dict_doc: dict[str, int | str] = {}
    for doc in list_doc:
        name = doc.pop("mpp")
        dict_doc[name] = doc["name"]
    group_lpu = []

    for res in result:
        if res["lpu"] not in group_lpu:
            group_lpu.append(res["lpu"])
        res["lpu_name"] = dict_lpu[res["lpu"]]
        res["name"] = dict_doc[res["mpp"]]
        lgot_edit(res)
        for key in dict_lgot:
            if f"ktn_{key}" in res:
                pass
            else:
                res[f"kol_{key}"] = 0
                res[f"stu_{key}"] = 0
    all_lgot: list = []
    for lpu in group_lpu:
        x = [x for x in result if x["lpu"] == lpu]
        compact_dict = {}
        for one in x:
            if one["mpp"] not in compact_dict:
                compact_dict[one["mpp"]] = {
                    "mpp": one["mpp"],
                    "name": one["name"],
                    "lpu_name": one["lpu_name"],
                    "kol_114": 0,
                    "stu_114": 0.0,
                    "kol_105": 0,
                    "stu_105": 0.0,
                    "kol_15": 0,
                    "stu_15": 0.0,
                    "kol_14": 0,
                    "stu_14": 0.0,
                }
                for key in dict_lgot:
                    if key in lgot_114:
                        compact_dict[one["mpp"]]["kol_114"] += one[f"kol_{key}"]
                        compact_dict[one["mpp"]]["stu_114"] += one[f"stu_{key}"]
                    elif key in lgot_105:
                        compact_dict[one["mpp"]]["kol_105"] += one[f"kol_{key}"]
                        compact_dict[one["mpp"]]["stu_105"] += one[f"stu_{key}"]
                    elif key in lgot_15:
                        compact_dict[one["mpp"]]["kol_15"] += one[f"kol_{key}"]
                        compact_dict[one["mpp"]]["stu_15"] += one[f"stu_{key}"]
                    elif key in lgot_14:
                        compact_dict[one["mpp"]]["kol_14"] += one[f"kol_{key}"]
                        compact_dict[one["mpp"]]["stu_14"] += one[f"stu_{key}"]
        compact_list = []
        for key, value in compact_dict.items():  # noqa: B007
            compact_list.append(value)
        all_lgot.append(compact_list)

    return JsonResponse({"status": "ok", "lgot_in_work": all_lgot})


def image_count_update() -> None:
    images_all = Images.objects.all()
    for image in images_all:
        nar = image.etap
        nar.image_count = nar.image_count + 1
        nar.save()


def import_nars() -> None:  # noqa: PLR0912, C901, PLR0915
    naryad_from_1c = pd.read_excel("data.xlsx", sheet_name="Лист1")
    result = naryad_from_1c.to_dict("records")
    doc_set = set()
    lpu_set = set()
    print(len(result))

    for nar in result:
        usl_list = []
        if type(nar["usl"]) is float:  # noqa: E721
            continue
        if type(nar["usl"]) is str:  # noqa: E721
            s = nar["usl"].split("\n")
            while s:
                split_list = s.pop().split(";")
                split_list[2] = int(split_list[2])
                usl_list.append(split_list)
        if type(nar["dr"]) is not str and math.isnan(nar["dr"]):  # noqa: E721
            nar["dr"] = "23.04.2024 00:00:00"
        if type(nar["dr"]) is str:  # noqa: E721
            nar["dr"] = datetime.strptime(nar["dr"], "%d.%m.%Y %H:%M:%S")
        if nar["opl"] not in (3, 5, 10) and nar["opl"] in (
            "Наличные",
            "Наличные,Платежная карта",
            "Платежная карта",
        ):
            nar["opl"] = 10
        nar["dou"] = datetime.strptime(nar["dou1"], "%d.%m.%Y %H:%M:%S")
        nar["dou1"] = datetime.strptime(nar["dou1"], "%d.%m.%Y %H:%M:%S")
        nar["usl"] = usl_list
        # for nar in result:
        if nar["del"] == "Да":
            continue
        if nar["doc"] in doc_set or math.isnan(nar["stu2"]):
            continue
        if nar["stu2"] == 0:
            print("stu2 равно нулю", nar["nkv"])
            continue

        if type(nar["usl"]) is float:  # noqa: E721
            continue
        lpu_set.add(nar["lpu"])
        if nar["nkv"] == "A3923":
            print("not exists in db", nar)
        if It_lab.objects.filter(nkv=nar["nkv"]).first() is not None:
            naryad = It_lab.objects.filter(nkv=nar["nkv"]).first()
            if naryad.dzr is not None:
                print(nar["nkv"], naryad.stu, "Уже закрыт")
            if naryad.stu == nar["stu1"]:
                print(nar["nkv"], naryad.stu, "Уже есть, сумма сходится")
                continue
            usls_in_db = Pl_uslp.objects.filter(idkv=nar["nkv"])
            summa = 0
            for usl_in_db in usls_in_db:
                usluga = Uslugi.objects.filter(kusl=usl_in_db.kusl).first()
                if usluga is None:
                    print(usl_in_db, "Usluga not found")
                summa += usluga.trf * usl_in_db.kol
            if nar["stu1"] != summa:
                print("Суммы: ", nar["nkv"], nar["stu1"], summa)
                Pl_uslp.objects.filter(idkv=nar["nkv"]).delete()
                for usl in nar["usl"]:
                    usluga = Uslugi.objects.filter(kusl=usl[0]).first()
                    if usluga is None:
                        print("Нет услуги", nar["nkv"], usl[0])
                        continue
                    Pl_uslp.objects.create(
                        idkv=naryad.nkv,
                        naryad=naryad,
                        kusl=usluga.kusl,
                        usl=usluga.usl,
                        nusl=usluga.nusl,
                        kol=usl[2],
                        uet=usluga.uet,
                        price=usluga.trf,
                        stu=usl[2] * usluga.trf,
                    )
            continue
        patient = Patient.objects.filter(
            fam=nar["fam"], im=nar["im"], ot=nar["ot"],
        ).first()
        doctor_user_sdl = User_sdl.objects.filter(doc=nar["doc2"])
        if len(doctor_user_sdl) > 1:
            print(nar, "multiple user_sdl by doc")
            continue
        if doctor_user_sdl.first() is None:
            continue
        if patient is None:
            print(
                nar["nkv"], "none patient", nar["fam"], nar["im"], nar["ot"], nar["dr"],
            )
            patient = Patient.objects.create(
                fam=nar["fam"], im=nar["im"], ot=nar["ot"], dr=nar["dr"],
            )
        doctor_user_sdl: User_sdl = doctor_user_sdl.first()
        access = doctor_user_sdl.access_list()
        profile_otd = 0
        if "doc" in access or "zav_ort" in access:
            profile_otd = 2
        elif "doc-ortodont" in access:
            profile_otd = 3
        doctor_user: MyUser = doctor_user_sdl.user
        if nar["lpu"] == 'ГАУЗ "ККСП", филиал г.Березовский, пр. Шахтеров 1':
            lpu = Spr_lpu.objects.get(lpu=3)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал пгт. Яшкино, ул. Шиферная 26':
            lpu = Spr_lpu.objects.get(lpu=32)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал 50 лет Октября, 18':
            lpu = Spr_lpu.objects.get(lpu=162)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал г.Топки, ул. Революции 1':
            lpu = Spr_lpu.objects.get(lpu=28)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал Инициативная, 16Б':
            lpu = Spr_lpu.objects.get(lpu=245)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал Ленинградский, 41':
            lpu = Spr_lpu.objects.get(lpu=165)
        elif nar["lpu"] == 'ГАУЗ "ККСП"':
            lpu = Spr_lpu.objects.get(lpu=164)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал Новогодняя, 1':
            lpu = Spr_lpu.objects.get(lpu=243)
        elif nar["lpu"] == 'ГАУЗ "ККСП", филиал Невьянская, 1Б':
            lpu = Spr_lpu.objects.get(lpu=164)
        else:
            print(
                "Нет ЛПУ: ",
                nar["nkv"],
                nar["doc"],
                nar["stu1"],
                "руб.",
                "lpu: ",
                nar["lpu"],
            )
            lpu = Spr_lpu.objects.get(lpu=164)
        summa = 0
        for usl in nar["usl"]:
            usluga = Uslugi.objects.filter(kusl=usl[0]).first()
            if usluga is None:
                print(usl, "Usluga not found")
            summa += usluga.trf * usl[2]
        if nar["stu1"] != summa:
            print(nar["nkv"], "Сумма не сошлась", nar["stu1"], summa)
            continue
        opl = Spr_opl.objects.get(opl=nar["opl"])
        sdl_set = Sdl_set.objects.create(doc=doctor_user.mpp)
        # profile_otd = 3
        naryad = It_lab.objects.create(
            lpu=lpu,
            patient=patient,
            idkv=nar["nkv"],
            nkv=nar["nkv"],
            dou=nar["dou"],
            stu=nar["stu1"],
            opl=opl,
            user_etap_link=doctor_user,
            naryad_doc=doctor_user_sdl,
            mpp_etap=doctor_user.mpp,
            sdl_etap=Spr_sdl.objects.get(sdl=1),
            sdl_set=sdl_set,
            container=Container.objects.get(id=0),
            laboratory=False,
            profile_otd=profile_otd,
        )
        for usl in nar["usl"]:
            usluga = Uslugi.objects.get(kusl=usl[0])
            Pl_uslp.objects.create(
                idkv=naryad.idkv,
                naryad=naryad,
                kusl=usluga.kusl,
                usl=usluga.usl,
                nusl=usluga.nusl,
                kol=usl[2],
                uet=usluga.uet,
                price=usluga.trf,
            )


def non_laboratory_naryads() -> None:
    not_lab_usls = (
        "2.1.2",
        "Л2.1.2",
        "2.1.1",
        "Л2.1.1",
        "2.3.8",
        "Л2.3.8",
        "2.3.9",
        "Л2.3.9",
        "2.3.11",
        "Л2.3.11",
        "2.3.10",
        "Л2.3.10",
    )
    list_nars_for_disable = []
    nars = It_lab.objects.filter(laboratory=True, dzr__isnull=True)
    print(len(nars))
    nars_usl = It_lab.objects.filter(laboratory=False, dzr__isnull=True)
    print(len(nars_usl))
    for nar in nars:
        usls = Pl_uslp.objects.filter(naryad=nar)
        lab = False
        for usl in usls:
            if usl.kusl not in not_lab_usls:
                lab = True
                break
        if lab is False:
            list_nars_for_disable.append(nar.nkv)
    print(len(list_nars_for_disable))
    It_lab.objects.filter(
        laboratory=True, dzr__isnull=True, nkv__in=list_nars_for_disable,
    ).update(laboratory=False)
    print(len(It_lab.objects.filter(laboratory=True, dzr__isnull=True)))


def update_pluslp(nkv_old, nkv_new):  # noqa: ANN201
    naryad = It_lab.objects.filter(nkv=nkv_old).first()
    if naryad is None:
        print(nkv_old, "is none")
        return
    naryad.nkv = nkv_new
    naryad.idkv = nkv_new
    naryad.save()
    usls = Pl_uslp.objects.filter(naryad__nkv=nkv_old)
    for usl in usls:
        usl.idkv = nkv_new
        usl.save()


def send_mail2() -> None:
    send_mail(
        "Тема", "Тело письма", settings.EMAIL_HOST_USER, ["anti-kirill@yandex.ru"],
    )


def check_stu_usl(naryad: It_lab, count: int) -> None:
    usls = Pl_uslp.objects.filter(naryad=naryad)
    summa = 0
    for usl in usls:
        usluga = Uslugi.objects.filter(kusl=usl.kusl).first()
        if usluga is None:
            print(usl, "Usluga not found")
        summa += usluga.trf * usl.kol
    if summa != naryad.stu:
        print(f"{count}.", naryad.nkv, "Сумма не сошлась", summa, naryad.stu)
        return 1
    return 0


def naryads_check_stu() -> None:
    count = 1
    nars = It_lab.objects.filter(dzr__isnull=True, dou__range=("2024-03-20", "2024-05-30"))
    list_nar = []
    for nar in nars:
        count_in = check_stu_usl(nar, count)
        if count_in:
            list_nar.append((nar.nkv, nar.opl.name_opl, nar.dou, nar.patient, nar.naryad_doc))
            count += 1
    print(list_nar)


def pl_uslp_zp_update() -> None:
    naryads = It_lab.objects.filter(pdzr__range=("2024-04-20", "2024-05-27"))
    for nar in naryads:
        usls = Pl_uslp.objects.filter(naryad=nar)
        for usl in usls:
            zp_tarif_for_pluslp(usl, nar)


def usl_update_stu_lab(usluga: Pl_uslp, naryad: It_lab, sdl: int) -> None:
    zusl = Ztarifs.objects.filter(
            usl__kusl=usluga.kusl, sdl__sdl=sdl, dk__isnull=True,
        ).first()
    if zusl is not None:
        if sdl == 35:  # noqa: PLR2004
            usluga.tech = zusl.trf_zp * usluga.kol
        if sdl == 36:  # noqa: PLR2004
            usluga.pol = zusl.trf_zp * usluga.kol
        if sdl == 37:  # noqa: PLR2004
            usluga.lit = zusl.trf_zp * usluga.kol
        if sdl == 38:  # noqa: PLR2004
            usluga.cadcam = zusl.trf_zp * usluga.kol
        usluga.save()
        if not naryad.laboratory:
            naryad.laboratory = True
            naryad.save()

def zp_tarif_for_pluslp(usluga: Pl_uslp, naryad: It_lab) -> None:
    usl_update_stu_lab(usluga, naryad, 35)
    usl_update_stu_lab(usluga, naryad, 36)
    usl_update_stu_lab(usluga, naryad, 37)
    usl_update_stu_lab(usluga, naryad, 38)


@receiver(post_save, sender=Pl_uslp)
def alert_user(sender, instance, created, **kwargs) -> None:  # noqa: ANN003, ARG001
    if created:
        zp_tarif_for_pluslp(instance, instance.naryad)


@receiver(pre_delete, sender=Buhreport)
def buhreport_delete(sender, instance, **kwargs) -> None:  # noqa: ARG001, ANN003
    # Pass false so FileField doesn't save the model.
    instance.file.delete(False)  # noqa: FBT003


def money_spec_dict_exists(x, y) -> dict:
                    x["lab_lgot"] += y["lab_lgot"]
                    x["lab_vt"] += y["lab_vt"]
                    x["lab_pd"] += y["lab_pd"]
                    x["lab_itog"] += y["lab_itog"]
                    return x


def money_spec_dict_not_exists(y) -> dict:
                    x = {}
                    x["mpp"] = y["mpp"]
                    x["fio"] = y["fio"]
                    x["dolzh"] = y["dolzh"]
                    x["lab_lgot"] = y["lab_lgot"]
                    x["lab_vt"] = y["lab_vt"]
                    x["lab_pd"] = y["lab_pd"]
                    x["lab_itog"] = y["lab_itog"]
                    return x


def create_buh_report(year: int, month: int, podr: int, profile: int, dn_pl: date, dk_pl: date, dn_lg: date, dk_lg: date) -> None:  # noqa: C901, PLR0912, PLR0915
    print(dn_pl, dk_pl, dn_lg, dk_lg)
    print("podr: ", podr)
    if podr > 1:
        nars = It_lab.objects.filter(lpu__lpu=podr, profile_otd=profile).filter((Q(dzr__range=(dn_pl, dk_pl)) & Q(opl__opl__gte=2)) | (Q(dzr__range=(dn_lg, dk_lg)) & Q(opl__opl=1)))
    docs = {}
    techs = {}
    pols = {}
    lits = {}
    cadcams = {}
    zp_techs = {}
    zp_pols = {}
    zp_lits = {}
    zp_cadcams = {}
    for nar in nars:
        doc = nar.money_for_doc()
        if doc:
            if doc["mpp"] in docs:
                x = docs[doc["mpp"]]
                x["usl_lgot"] += doc["usl_lgot"]
                x["usl_vt"] += doc["usl_vt"]
                x["usl_pd"] += doc["usl_pd"]
                x["usl_itog"] += doc["usl_itog"]
                docs[doc["mpp"]] = money_spec_dict_exists(x, doc)
            else:
                x = {}
                x["mpp"] = doc["mpp"]
                x["fio"] = doc["fio"]
                x["dolzh"] = doc["dolzh"]
                x["usl_lgot"] = doc["usl_lgot"]
                x["usl_vt"] = doc["usl_vt"]
                x["usl_pd"] = doc["usl_pd"]
                x["usl_itog"] = doc["usl_itog"]
                x["lab_lgot"] = doc["lab_lgot"]
                x["lab_vt"] = doc["lab_vt"]
                x["lab_pd"] = doc["lab_pd"]
                x["lab_itog"] = doc["lab_itog"]
                docs[doc["mpp"]] = x
        tech = nar.money_for_tech()
        if tech:
            if tech["mpp"] in techs:
                techs[tech["mpp"]] = money_spec_dict_exists(techs[tech["mpp"]], tech)
            else:
                techs[tech["mpp"]] = money_spec_dict_not_exists(tech)
        pol = nar.money_for_pol()
        if pol:
            if pol["mpp"] in pols:
                pols[pol["mpp"]] = money_spec_dict_exists(pols[pol["mpp"]], pol)
            else:
                pols[pol["mpp"]] = money_spec_dict_not_exists(pol)
        lit = nar.money_for_lit()
        if lit:
            if lit["mpp"] in lits:
                lits[lit["mpp"]] = money_spec_dict_exists(lits[lit["mpp"]], lit)
            else:
                lits[lit["mpp"]] = money_spec_dict_not_exists(lit)
        cadcam = nar.money_for_cadcam()
        if cadcam:
            if cadcam["mpp"] in cadcams:
                cadcams[cadcam["mpp"]] = money_spec_dict_exists(cadcams[cadcam["mpp"]], cadcam)
            else:
                cadcams[cadcam["mpp"]] = money_spec_dict_not_exists(cadcam)
        zp_tech = nar.zp_for_tech()
        if zp_tech:
            if zp_tech["mpp"] in zp_techs:
                zp_techs[zp_tech["mpp"]] = money_spec_dict_exists(zp_techs[zp_tech["mpp"]], zp_tech)
            else:
                zp_techs[zp_tech["mpp"]] = money_spec_dict_not_exists(zp_tech)
        zp_pol = nar.zp_for_pol()
        if zp_pol:
            if zp_pol["mpp"] in zp_pols:
                zp_pols[zp_pol["mpp"]] = money_spec_dict_exists(zp_pols[zp_pol["mpp"]], zp_pol)
            else:
                zp_pols[zp_pol["mpp"]] = money_spec_dict_not_exists(zp_pol)
        zp_lit = nar.zp_for_lit()
        if zp_lit:
            if zp_lit["mpp"] in zp_lits:
                zp_lits[zp_lit["mpp"]] = money_spec_dict_exists(zp_lits[zp_lit["mpp"]], zp_lit)
            else:
                zp_lits[zp_lit["mpp"]] = money_spec_dict_not_exists(zp_lit)
        zp_cadcam = nar.zp_for_cadcam()
        if zp_cadcam:
            if zp_cadcam["mpp"] in zp_cadcams:
                zp_cadcams[zp_cadcam["mpp"]] = money_spec_dict_exists(zp_cadcams[zp_cadcam["mpp"]], zp_cadcam)
            else:
                zp_cadcams[zp_cadcam["mpp"]] = money_spec_dict_not_exists(zp_cadcam)
    list_docs = list(docs.values())
    list_techs = list(techs.values())
    list_pols = list(pols.values())
    list_lits = list(lits.values())
    list_cadcams = list(cadcams.values())
    list_zp_techs = list(zp_techs.values())
    list_zp_pols = list(zp_pols.values())
    list_zp_lits = list(zp_lits.values())
    list_zp_cadcams = list(zp_cadcams.values())
    try:
        report = Buhreport.objects.create(
            year=year,
            month=month,
            profile=profile,
            podr=podr,
            list_docs=list_docs,
            list_techs=list_techs,
            list_pols=list_pols,
            list_lits=list_lits,
            list_cadcams=list_cadcams,
            list_zp_techs=list_zp_techs,
            list_zp_pols=list_zp_pols,
            list_zp_lits=list_zp_lits,
            list_zp_cadcams=list_zp_cadcams)
        to_xls(
            report=report,
            dzr_start=dn_pl,
            dzr_end=dk_pl,
            dzr_lgot_start=dn_lg,
            dzr_lgot_end=dk_lg,
            list_docs=list_docs,
            list_techs=list_techs,
            list_pols=list_pols,
            list_lits=list_lits,
            list_cadcams=list_cadcams,
            list_zp_techs=list_zp_techs,
            list_zp_pols=list_zp_pols,
            list_zp_lits=list_zp_lits,
            list_zp_cadcams=list_zp_cadcams,
            )
    except Exception:
        logging.exception("create_buh_report")
